package cn.getech.data.development.service.impl;

import cn.getech.data.development.constant.ConnectTypeEnum;
import cn.getech.data.development.mapper.dataMap.SearchHistoryMapper;
import cn.getech.data.development.service.ConfConnectService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

/**
 * @Author: xff
 * @Date: 2021/9/23 11:22
 * @Description:
 */
@Slf4j
@Service
public class EsCategoryService {

    @Resource
    private RestHighLevelClient client ;

    private final RequestOptions options = RequestOptions.DEFAULT;

    @Autowired
    private ConfConnectService confConnectService;


    @Value("${elasticsearch.fieldIndexName}")
    private String fieldIndexName;

    @Value("${elasticsearch.targetIndexName}")
    private String targetIndexName;

    @Value("${elasticsearch.serviceIndexName}")
    private String serviceIndexName;

    @Value("${elasticsearch.dataSourceIndexName}")
    private String dataSourceIndexName;

    @Value("${elasticsearch.taskIndexName}")
    private String taskIndexName;
    /**
     * 查询(指标,数据源, 数据服务,采集任务,字段)
     */
    public Map<String,Object> searchPage (Map<String,Object> map) {
        Map<String,Object> resultMap = new HashMap<>();
        String indexName = null;//索引名称
        // 查询条件,指定时间并过滤指定字段值
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

        if ("targetName".equals(map.get("searchType"))) {
            //指标
            indexName = targetIndexName;
            Map<String,Object> targetNameMap  = buildTargetName(indexName, map, boolQueryBuilder);
            resultMap.put("targetNameMap",targetNameMap);
        }  else if("dataSource".equals(map.get("searchType"))){
            //数据源
            indexName = dataSourceIndexName;
            Map<String,Object> dataSourceMap  = buildDataSource(indexName, map, boolQueryBuilder);
            resultMap.put("dataSourceMap",dataSourceMap);
        }else if("dataService".equals(map.get("searchType"))){
            //数据服务
            indexName = serviceIndexName;
            Map<String,Object> serviceMap = buildService(indexName, map, boolQueryBuilder);
            resultMap.put("serviceMap",serviceMap);
        }else if("collectTask".equals(map.get("searchType"))){
            //采集任务
            indexName = taskIndexName;
            Map<String,Object> taskMap = buildTask(indexName,map, boolQueryBuilder);
            resultMap.put("taskMap",taskMap);
        }else {
            //表或者字段
            indexName = fieldIndexName;
            Map<String,Object> fieldMap = buildFiled(indexName, map, boolQueryBuilder);
            resultMap.put("fieldMap",fieldMap);
        }
        sourceBuilder.query(boolQueryBuilder);
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("*").requireFieldMatch(false).preTags("<span style='color:red'>").postTags("</span>");
        sourceBuilder.from((Integer.parseInt(map.get("page")+"")-1) * Integer.parseInt(map.get("limit")+""));
        sourceBuilder.size(Integer.parseInt(map.get("limit")+""));
        sourceBuilder.sort("_score");
        sourceBuilder.highlighter(highlightBuilder);
        SearchRequest searchRequest = new SearchRequest(indexName);
        searchRequest.source(sourceBuilder);
        try {
            SearchResponse searchResp = client.search(searchRequest, options);
            List<Map<String,Object>> data = new ArrayList<>() ;
            SearchHit[] searchHitArr = searchResp.getHits().getHits();
            for (SearchHit searchHit:searchHitArr){
                Map<String, Object> source = searchHit.getSourceAsMap();
                if(indexName.equals(taskIndexName)&&source.containsKey("task_name")){
                    //source.put("taskname", highlightFields.get("taskname").fragments()[0].toString());  //高亮字段替换掉原本的内容
                    source = tasknameCamelCase(source);
                    Integer taskTypeId =(Integer) source.get("taskTypeId");
                    switch (taskTypeId){
                        case 0:source.put("name","手动采集");source.put("taskType","手动采集");break;
                        case 1:source.put("name","自动采集");source.put("taskType","自动采集");break;
                        case 2:source.put("name","接口");source.put("taskType","接口");break;
                    }
                    if(source.get("sourceTypeId")!=null){
                        String sourceType = dbTypeTransfor(Integer.parseInt(source.get("sourceTypeId") + ""));
                        source.put("sourceType",sourceType);
                    }
                }
                if(indexName.equals(serviceIndexName)&&source.containsKey("service_name")){
                    //source.put("servicename", highlightFields.get("servicename").fragments()[0].toString());  //高亮字段替换掉原本的内容
                    source = servicenameCamelCase(source);
                }
                if(indexName.equals(dataSourceIndexName)&&source.containsKey("name")){
                    //source.put("datasource", highlightFields.get("servicenames").fragments()[0].toString());  //高亮字段替换掉原本的内容
                    source = datasourceCamelCase(source);
                    String relationContent = getRelationContent(source);
                    source.put("relationContent",relationContent);
                }
                if(indexName.equals(targetIndexName)&&source.containsKey("target_name")){
                    //source.put("targetname", highlightFields.get("targetname").fragments()[0].toString());  //高亮字段替换掉原本的内容
                    source = targetnameCamelCase(source);
                }
                if(indexName.equals(fieldIndexName)&&source.containsKey("field_name")){
                    //source.put("fieldname", highlightFields.get("fieldname").fragments()[0].toString());  //高亮字段替换掉原本的内容
                    source = fieldnameCamelCase(source);
                    Integer tableType = Integer.parseInt(source.get("tableType")+"");
                    String tableTypeStr = tableType==1?"离线表":"实时表";
                    source.put("tableTypeStr",tableTypeStr);
                }
                data.add(source);
            }
            resultMap.put("currPage",Integer.parseInt(map.get("page")+""));
            resultMap.put("pageSize",Integer.parseInt(map.get("limit")+""));
            long total = searchResp.getHits() == null ? 0 : searchResp.getHits().getTotalHits().value;
            resultMap.put("totalCount",total);
            resultMap.put("totalPage",(total+ Integer.parseInt(map.get("limit")+"") - 1)/Integer.parseInt(map.get("limit")+""));
            resultMap.put("list",data);


            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null ;
    }

    private Map<String, Object> buildService(String indexName, Map<String, Object> map, BoolQueryBuilder boolQueryBuilder) {
        BoolQueryBuilder serviceBoolQueryBuilder = new BoolQueryBuilder();
        SearchSourceBuilder serviceBuilderSource = new SearchSourceBuilder();
        if (!StringUtils.isEmpty(map.get("dataService")+"")){
            boolQueryBuilder.must(QueryBuilders.wildcardQuery("service_name","*"+map.get("dataService")+"*"));
            serviceBoolQueryBuilder.must(QueryBuilders.wildcardQuery("service_name","*"+map.get("dataService")+"*"));
        }
        if (map.get("serviceGroup")!=null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("group_id", map.get("serviceGroup")));
        }
        if (map.get("dataSourceType")!=null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("type_id", map.get("dataSourceType")));
        }
        if (map.get("ids")!=null){
            List<Integer> ids = (List<Integer>) map.get("ids");
            boolQueryBuilder.filter(QueryBuilders.termsQuery("id", ids));
            serviceBoolQueryBuilder.filter(QueryBuilders.termsQuery("id", ids));
        }
        serviceBuilderSource.from(0);
        serviceBuilderSource.size(1000);
        serviceBuilderSource.query(serviceBoolQueryBuilder);
        SearchRequest fieldSearchRequestSource = new SearchRequest(indexName);
        fieldSearchRequestSource.source(serviceBuilderSource.trackTotalHits(true));
        SearchResponse fieldSearchRespSource = null;
        try {
            fieldSearchRespSource = client.search(fieldSearchRequestSource, options);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Set<Integer> dataSourceSet= Sets.newHashSet();
        Set<Integer> serviceSet = Sets.newHashSet();
        List dataSourceList = new ArrayList();
        List serviceList = new ArrayList();
        SearchHit[] searchHitArr = fieldSearchRespSource.getHits().getHits();
        for (SearchHit searchHit : searchHitArr) {
            Map<String, Object> source = searchHit.getSourceAsMap();
            Integer typeId = (Integer) source.get("type_id");
            dataSourceSet.add(typeId);

            Integer groupId = (Integer) source.get("group_id");
            serviceSet.add(groupId);
        }
        for (Integer typeId : dataSourceSet) {
            Map<String, Object> dataSourceMap = Maps.newHashMap();
            dataSourceMap.put("id",typeId);
            dataSourceMap.put("name",dbTypeTransfor(typeId));
            dataSourceList.add(dataSourceMap);
        }
        for (Integer groupId : serviceSet) {
            Map<String, Object> serviceMap = Maps.newHashMap();
            serviceMap.put("id",groupId);
            serviceMap.put("name",this.searchHistoryMapper.queryNameById(groupId));
            serviceList.add(serviceMap);
        }
        Map<String,Object> dataMap = new HashMap<>();
        dataMap.put("dataSource",dataSourceList);
        dataMap.put("service",serviceList);
        return dataMap;
    }

    private Map<String, Object> buildTask(String indexName, Map<String, Object> map, BoolQueryBuilder boolQueryBuilder) {
        BoolQueryBuilder taskBoolQueryBuilder = new BoolQueryBuilder();
        SearchSourceBuilder taskBuilderSource = new SearchSourceBuilder();
        if (!StringUtils.isEmpty(map.get("collectTask")+"")){
            boolQueryBuilder.must(QueryBuilders.wildcardQuery("task_name","*"+map.get("collectTask")+"*"));
            taskBoolQueryBuilder.must(QueryBuilders.wildcardQuery("task_name","*"+map.get("collectTask")+"*"));
        }
        if (map.get("dataSourceType")!=null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("source_type_id", map.get("dataSourceType")));
        }
        if (map.get("taskType")!=null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("task_type_id", map.get("taskType")));
        }
        if (map.get("ids")!=null){
            List<Integer> ids = (List<Integer>) map.get("ids");
            boolQueryBuilder.filter(QueryBuilders.termsQuery("id", ids));
            taskBoolQueryBuilder.filter(QueryBuilders.termsQuery("id", ids));

        }
        taskBuilderSource.from(0);
        taskBuilderSource.size(1000);
        taskBuilderSource.query(taskBoolQueryBuilder);
        SearchRequest fieldSearchRequestSource = new SearchRequest(indexName);
        fieldSearchRequestSource.source(taskBuilderSource.trackTotalHits(true));
        SearchResponse fieldSearchRespSource = null;
        try {
            fieldSearchRespSource = client.search(fieldSearchRequestSource, options);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Set<String> dataSourceSet= Sets.newHashSet();
        Set<Integer> taskSet = Sets.newHashSet();
        List dataSourceList = new ArrayList();
        List taskList = new ArrayList();
        SearchHit[] searchHitArr = fieldSearchRespSource.getHits().getHits();
        for (SearchHit searchHit : searchHitArr) {
            Map<String, Object> source = searchHit.getSourceAsMap();
            Integer id =(Integer) source.get("task_type_id");
            if (id!=null){
                taskSet.add(id);
            }
            String sourceType =(String) source.get("source_type_id");
            if (!StringUtils.isEmpty(sourceType)){
                dataSourceSet.add(sourceType);
            }
        }
        for (String sourceType : dataSourceSet) {
            String sourceTypeNmae = dbTypeTransfor(Integer.valueOf(sourceType));
            Map<String, Object> dataSourceMap = Maps.newHashMap();
            dataSourceMap.put("id",sourceType);
            dataSourceMap.put("name",sourceTypeNmae);
            dataSourceList.add(dataSourceMap);
        }
        for (Integer id : taskSet) {
            Map<String, Object> taskMap = Maps.newHashMap();
            taskMap.put("id",id);
            switch (id){
                case 0:taskMap.put("name","手动采集");break;
                case 1:taskMap.put("name","自动采集");break;
                case 2:taskMap.put("name","接口");break;
            }
            taskList.add(taskMap);
        }
        Map<String,Object> dataMap = new HashMap<>();
        dataMap.put("dataSource",dataSourceList);
        dataMap.put("task",taskList);
        return dataMap;

    }

    private Map<String,Object> buildFiled(String indexName, Map<String, Object> map, BoolQueryBuilder boolQueryBuilder) {
        BoolQueryBuilder fieldBoolQueryBuilder = new BoolQueryBuilder();
        SearchSourceBuilder fieldBuilderSource = new SearchSourceBuilder();
        if (!StringUtils.isEmpty(map.get("fieldName")+"")){
            boolQueryBuilder.must(QueryBuilders.wildcardQuery("fieldName","*"+map.get("fieldName")+"*"));
            fieldBoolQueryBuilder.must(QueryBuilders.wildcardQuery("fieldName","*"+map.get("fieldName")+"*"));
        }
        if (map.get("projectId")!=null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("project_ids",map.get("projectId")));
        }
        if (map.get("dbName")!=null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("db_name",map.get("dbName")));
        }
        fieldBuilderSource.from(0);
        fieldBuilderSource.size(1000);
        fieldBuilderSource.query(fieldBoolQueryBuilder);
        SearchRequest fieldSearchRequestSource = new SearchRequest(indexName);
        fieldSearchRequestSource.source(fieldBuilderSource.trackTotalHits(true));
        SearchResponse fieldSearchRespSource = null;
        try {
            fieldSearchRespSource = client.search(fieldSearchRequestSource, options);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Set<String> databaseSet= Sets.newHashSet();
        Set<Integer> projectIdSet = Sets.newHashSet();
        Set<Integer> subjectIdSet = Sets.newHashSet();
        SearchHit[] searchHitArr = fieldSearchRespSource.getHits().getHits();
        for (SearchHit searchHit : searchHitArr) {
            Map<String, Object> source = searchHit.getSourceAsMap();
            String dbName = (String) source.get("db_name");
            if (!StringUtils.isEmpty(dbName)){
                databaseSet.add(dbName);
            }

            String projectIds = (String) source.get("project_ids");
            if (!StringUtils.isEmpty(projectIds)){
                for (String id : projectIds.split(",")) {
                    projectIdSet.add(Integer.parseInt(id));
                }
            }
            String subjectIds = (String) source.get("subject_ids");
            if (!StringUtils.isEmpty(subjectIds)){
                for (String id : subjectIds.split(",")) {
                    subjectIdSet.add(Integer.parseInt(id));
                }
            }
        }
        List<Map<String, Object>> procList=Lists.newArrayList();
        List<Map<String, Object>> subjectList=Lists.newArrayList();
        List<JSONObject> databases= Lists.newArrayList();

        if (CollectionUtils.isNotEmpty(projectIdSet)) {
            procList = this.searchHistoryMapper.selectProcListList(projectIdSet);
        }
        if (CollectionUtils.isNotEmpty(subjectIdSet)) {
            subjectList = this.searchHistoryMapper.selectSubjectList(subjectIdSet);
        }
        for (String s : databaseSet) {
            JSONObject db = new JSONObject();
            db.put("id", s);
            db.put("name", s);
            databases.add(db);
        }

        Map<String,Object> dataMap = new HashMap<>();
        dataMap.put("project",procList);
        dataMap.put("database",databases);
        dataMap.put("subject",subjectList);
        return dataMap;
    }

    @Autowired
    private SearchHistoryMapper searchHistoryMapper;

    private Map<String, Object> buildTargetName(String indexName,Map<String, Object> map, BoolQueryBuilder boolQueryBuilder) {
        BoolQueryBuilder targetNameBoolQueryBuilder = new BoolQueryBuilder();
        SearchSourceBuilder targetNameBuilderSource = new SearchSourceBuilder();
        if (!StringUtils.isEmpty(map.get("targetName")+"")){
            boolQueryBuilder.must(QueryBuilders.wildcardQuery("target_name","*"+map.get("targetName")+"*"));
            targetNameBoolQueryBuilder.must(QueryBuilders.wildcardQuery("target_name","*"+map.get("targetName")+"*"));

        }
        if (map.get("subjectId")!=null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("subject_ids",map.get("subjectId")));
        }
        if (map.get("isOnlyShowCore")!=null&&"2".equals(map.get("isOnlyShowCore")+"")){
            boolQueryBuilder.filter(QueryBuilders.termQuery("is_core",Integer.parseInt(map.get("isOnlyShowCore")+"")));
        }
        if (map.get("tenantId")!=null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("tenant_id",map.get("tenantId")));
            targetNameBoolQueryBuilder.filter(QueryBuilders.termQuery("tenant_id",map.get("tenantId")));

        }
        targetNameBuilderSource.from(0);
        targetNameBuilderSource.size(1000);
        targetNameBuilderSource.query(targetNameBoolQueryBuilder);
        SearchRequest targetNameSearchRequestSource = new SearchRequest(indexName);
        targetNameSearchRequestSource.source(targetNameBuilderSource.trackTotalHits(true));
        SearchResponse dataSourceSearchRespSource = null;
        try {
            dataSourceSearchRespSource = client.search(targetNameSearchRequestSource, options);
        } catch (IOException e) {
            e.printStackTrace();
        }
        SearchHit[] searchHitArr = dataSourceSearchRespSource.getHits().getHits();
        Set<String> targetTypeSet= Sets.newHashSet();
        Set<Integer> subjectIdSet = Sets.newHashSet();

        for (SearchHit searchHit : searchHitArr) {
            Map<String, Object> source = searchHit.getSourceAsMap();
            String subjectIds = (String) source.get("subject_ids");
            if(!StringUtils.isEmpty(subjectIds)){
                for (String id : subjectIds.split(",")) {
                    subjectIdSet.add(Integer.parseInt(id));
                }

            }
            String targetType = source.get("target_type")+"";
            targetTypeSet.add(targetType);
        }
        List<Map<String, Object>> subjectList=Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(subjectIdSet)) {
            subjectList = this.searchHistoryMapper.selectSubjectList(subjectIdSet);
        }
        List<JSONObject> targetTypeList= Lists.newArrayList();
        for (String s : targetTypeSet) {
            JSONObject db = new JSONObject();
            db.put("id", s);
            db.put("name", "1".equals(s) ? "原子指标" : "派生指标");
            targetTypeList.add(db);
        }
        Map<String,Object> dataMap = new HashMap<>();
        dataMap.put("subject",subjectList);
        dataMap.put("targetType",targetTypeList);
        return dataMap;
    }


    private Map<String, Object> buildDataSource(String indexName,Map<String, Object> map, BoolQueryBuilder boolQueryBuilder)
    {
        BoolQueryBuilder dataSourceBoolQueryBuilder = new BoolQueryBuilder();
        SearchSourceBuilder dataSourceSourceBuilderSource = new SearchSourceBuilder();
        if (!StringUtils.isEmpty(map.get("dataSource")+"")){
            boolQueryBuilder.must(QueryBuilders.wildcardQuery("name","*"+map.get("dataSource")+"*"));
            dataSourceBoolQueryBuilder.must(QueryBuilders.wildcardQuery("name","*"+map.get("dataSource")+"*"));
        }
        if (map.get("typeId")!=null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("type_id", map.get("typeId")));
        }
        if (map.get("ids")!=null){
            List<Integer> ids = (List<Integer>) map.get("ids");
            boolQueryBuilder.filter(QueryBuilders.termsQuery("id", ids));
            dataSourceBoolQueryBuilder.filter(QueryBuilders.termsQuery("id", ids));

        }
        if (map.get("procId")!=null){
            List<Integer> ids = confConnectService.queryIdsByProjectId(Integer.parseInt(map.get("procId")+""));
            boolQueryBuilder.filter(QueryBuilders.termsQuery("id", ids));
        }
        dataSourceSourceBuilderSource.from(0);
        dataSourceSourceBuilderSource.size(1000);
        dataSourceSourceBuilderSource.query(dataSourceBoolQueryBuilder);
        SearchRequest dataSourceSearchRequestSource = new SearchRequest(indexName);
        dataSourceSearchRequestSource.source(dataSourceSourceBuilderSource.trackTotalHits(true));
        SearchResponse dataSourceSearchRespSource = null;
        try {
            dataSourceSearchRespSource = client.search(dataSourceSearchRequestSource, options);
        } catch (IOException e) {
            e.printStackTrace();
        }
        SearchHit[] searchHitArr = dataSourceSearchRespSource.getHits().getHits();
        Set<String> dataSource = new HashSet<>();
        Set<String> project = new HashSet<>();
        for (SearchHit searchHit : searchHitArr) {
            Map<String, Object> source = searchHit.getSourceAsMap();
            if(source.get("type_id")!=null){
                String sourceType = dbTypeTransfor(Integer.parseInt(source.get("type_id") + ""));
                dataSource.add(sourceType);
            }
            if(source.get("proc_names")!=null){
                String[] procNames = source.get("proc_names").toString().split(",");
                for (String procName : procNames) {
                    project.add(procName);
                }
            }
        }
        Map<String,Object> dataMap = new HashMap<>();
        List<Map> dataSourceList = new ArrayList<>();
        for (String name : dataSource) {
            Map<String,Object> nameAndId = new HashMap<>();
            switch (name) {
                case "MySQL":
                    nameAndId.put("id", 1);
                    break;
                case "Oracle":
                    nameAndId.put("id", 2);
                    break;
                case "SQL_Server":
                    nameAndId.put("id", 3);
                    break;
                case "PostgreSQL":
                    nameAndId.put("id", 4);
                    break;
                case "FTP":
                    nameAndId.put("id", 5);
                    break;
                case "Kafka":
                    nameAndId.put("id", 6);
                    break;
                case "JieKou":
                    nameAndId.put("id", 7);
                    break;
                case "Sap":
                    nameAndId.put("id", 8);
                    break;
                case "WebService":
                    nameAndId.put("id", 9);
                    break;
                case "SAPHANA":
                    nameAndId.put("id", 10);
                    break;
                case "Hive":
                    nameAndId.put("id", 11);
                    break;
                case "ElasticSearch":
                    nameAndId.put("id", 12);
                    break;
                case "HBase":
                    nameAndId.put("id", 13);
                    break;
                case "Kudu":
                    nameAndId.put("id", 14);
                    break;
                case "ClickHouse":
                    nameAndId.put("id", 15);
                    break;
                case "MongoDB":
                    nameAndId.put("id", 17);
                    break;
                case "SFTP":
                    nameAndId.put("id", 18);
                    break;
            }
            nameAndId.put("name", name);
            dataSourceList.add(nameAndId);
        }

        List<Map> projectList = new ArrayList<>();
        for (String name : project) {
            Integer id = confConnectService.selectByName(name);
            Map<String,Object> projectMap = new HashMap<>();
            projectMap.put("id",id);
            projectMap.put("name",name);
            projectList.add(projectMap);
        }
        dataMap.put("dataSource",dataSourceList);
        dataMap.put("project",projectList);
        return dataMap;
    }





    private String dbTypeTransfor(Integer typeId){
        if(typeId==null){
            return null;
        }
        switch (typeId){
            case 1:return "MySQL";
            case 2:return "Oracle";
            case 3:return "SQL_Server";
            case 4:return "PostgreSQL";
            case 5:return "FTP";
            case 6:return "Kafka";
            case 7:return "JieKou";
            case 8:return "Sap";
            case 9:return "WebService";
            case 10:return "SAPHANA";
            case 11:return "Hive";
            case 12:return "ElasticSearch";
            case 13:return "HBase";
            case 14:return "Kudu";
            case 15:return "ClickHouse";
            case 16:return "Oracle";
            case 17:return "MongoDB";
            case 18:return "SFTP";
        }
        return null;
    }

    public Map<String,Object> fieldnameCamelCase(Map<String,Object> source){
        Map<String,Object> target = new HashMap<>();
        target.put("id",source.get("table_id"));
        target.put("fieldId",source.get("field_id"));
        target.put("dbName",source.get("db_name"));
        target.put("tableName",source.get("table_name"));
        target.put("fieldName",source.get("field_name"));
        target.put("tableAlias",source.get("table_alias"));
        target.put("tableType",source.get("table_type"));
        target.put("projectIds",source.get("project_ids"));
        target.put("tableDesc",source.get("table_desc"));
        target.put("subjectName",source.get("subject_name"));
        target.put("subjectIds",source.get("subject_ids"));
        target.put("createPerName",source.get("create_per_name"));
        target.put("viewsNum",source.get("views_num"));
        target.put("projectName",source.get("project_name"));
//                "targetName": null,
//                "quoteNum": null,
        return target;
    }


    public String snakeToCamel(String str)
    {
        StringBuilder builder = new StringBuilder(str);
        for (int i = 0; i < builder.length(); i++) {
            if (builder.charAt(i) == '_') {
                builder.deleteCharAt(i);
                builder.replace(i, i + 1, String.valueOf(Character.toUpperCase(builder.charAt(i))));
            }
        }
        return builder.toString();
    }
    public Map<String,Object> targetnameCamelCase(Map<String,Object> source){
        Map<String,Object> target = new HashMap<>();
        target.put("id",source.get("id"));
        target.put("targetName",source.get("target_name"));
        target.put("tenantId",source.get("tenant_id"));
        target.put("targetType",source.get("target_type"));
        target.put("subjectName",source.get("subject_name"));
        target.put("createPerName",source.get("create_per_name"));
        target.put("isCore",source.get("is_core"));
        target.put("subjectIds",source.get("subject_ids"));
        return target;
    }


    public Map<String,Object> servicenameCamelCase(Map<String,Object> source){
        Map<String,Object> target = new HashMap<>();
        target.put("id",source.get("id"));
        target.put("userNum",source.get("user_num"));
        target.put("tenantId",source.get("tenant_id"));
        target.put("description",source.get("description"));
        target.put("createName",source.get("create_name"));
        target.put("typeId",source.get("type_id"));
        target.put("groupId",source.get("group_id"));
        target.put("serviceName",source.get("service_name"));
        target.put("groupName",source.get("group_name"));
        if(source.get("type_id")!=null){
            String sourceType = dbTypeTransfor(Integer.parseInt(source.get("type_id") + ""));
            target.put("typeName",sourceType);
        }else{
            target.put("typeName",null);
        }
        return target;
    }


    public Map<String,Object> tasknameCamelCase(Map<String,Object> source){
        Map<String,Object> target = new HashMap<>();
        target.put("id",source.get("id"));
        target.put("taskName",source.get("task_name"));
        target.put("tenantId",source.get("tenant_id"));
        target.put("taskTypeId",source.get("task_type_id"));
        target.put("userName",source.get("user_name"));
        target.put("sourceTypeId",source.get("source_type_id"));
        target.put("runCount",source.get("run_count"));
        target.put("sourceId",source.get("source_id"));
        target.put("ownModule",source.get("own_module"));
        target.put("metadataBelongs",source.get("metadata_belongs"));
        return target;
    }

    public Map<String,Object> datasourceCamelCase(Map<String,Object> source){
        Map<String,Object> target = new HashMap<>();
        target.put("id",source.get("id"));
        target.put("topic",source.get("topic"));
        target.put("taskNames",source.get("task_names"));
        target.put("syncTaskNames",source.get("sync_task_names"));
        target.put("password",source.get("password"));
        target.put("port",source.get("port"));
        target.put("departmentId",source.get("department_id"));
        target.put("ruleNames",source.get("rule_names"));
        target.put("createPer",source.get("create_per"));
        target.put("createPerName",source.get("user_name"));
        target.put("serviceNames",source.get("service_names"));
        target.put("desc",source.get("desc"));
        target.put("modper",source.get("modper"));
        target.put("connecTenable",source.get("connec_tenable"));
        target.put("kafkaUrl",source.get("kafka_url"));
        target.put("host",source.get("host"));
        target.put("typeId",source.get("type_id"));
        target.put("ftpFileLocation",source.get("ftp_file_location"));
        target.put("tenantId",source.get("tenant_id"));
        target.put("webServiceUrl",source.get("web_service_url"));
        target.put("connectStatus",source.get("connect_status"));
        if(source.get("connect_status")!=null&&Integer.parseInt(source.get("connect_status")+"")==1){
            target.put("connectStatusStr","正常");
        }else {
            target.put("connectStatusStr","失败");
        }
        target.put("modTime",source.get("mod_time"));
        target.put("functionName",source.get("function_name"));
        target.put("interFaceUrl",source.get("inter_face_url"));
        target.put("dbName",source.get("db_name"));
        target.put("createTime",source.get("create_time"));
        target.put("requestType",source.get("request_type"));
        target.put("departMentName",source.get("depart_ment_name"));
        target.put("procNames",source.get("proc_names"));
        StringBuilder builder = new StringBuilder();
        if (StringUtils.isNotEmpty(source.get("proc_names")+"")) {
            builder.append("关联的项目:<br/>").append(source.get("proc_names")).append("<br/>");
        }
        if (StringUtils.isNotEmpty(source.get("task_names")+"")) {
            builder.append("关联的元数据采集任务:<br/>").append(source.get("task_names")).append("<br/>");
        }
        if (StringUtils.isNotEmpty(source.get("rule_names")+"")) {
            builder.append("关联的质量规则:<br/>").append(source.get("rule_names")).append("<br/>");
        }
        if (StringUtils.isNotEmpty(source.get("service_names")+"")) {
            builder.append("关联的数据服务:<br/>").append(source.get("service_names")).append("<br/>");
        }

        if (StringUtils.isNotEmpty(source.get("sync_task_names")+"")) {
            builder.append("关联的整库同步任务:<br/>").append(source.get("sync_task_names")).append("<br/>");
        }

        //1:使用中 2:未使用
        if (builder.length() > 0) {
            target.put("appState",1);
            target.put("appStateStr","使用中");
        }else {
            target.put("appState",2);
            target.put("appStateStr","未使用");
        }
        target.put("name",source.get("name"));
        target.put("departmentName",source.get("department_name"));
        target.put("connectEnable",source.get("connect_enable"));
        target.put("modPer",source.get("mod_per"));
        target.put("username",source.get("username"));
        target.put("interfaceUrl",source.get("interface_url"));

        if(source.get("type_id")!=null){
            switch (Integer.parseInt(source.get("type_id")+"")){
                case 1: target.put("typeName","MySQL");break;
                case 2: target.put("typeName","Oracle");break;
                case 3: target.put("typeName","SQL_Server");break;
                case 4: target.put("typeName","PostgreSQL");break;
                case 5: target.put("typeName","FTP");break;
                case 6: target.put("typeName","Kafka");break;
                case 7: target.put("typeName","JieKou");break;
                case 8: target.put("typeName","Sap");break;
                case 9: target.put("typeName","WebService");break;
                case 10: target.put("typeName","SAPHANA");break;
                case 11: target.put("typeName","Hive");break;
                case 12: target.put("typeName","ElasticSearch");break;
                case 13: target.put("typeName","HBase");break;
                case 14: target.put("typeName","Kudu");break;
                case 15: target.put("typeName","ClickHouse");break;
                case 17: target.put("typeName","MongoDB");break;
                case 18: target.put("typeName","SFTP");break;
            }
        }

        String info = null;
        if (Objects.equals(ConnectTypeEnum.Kafka.getCode(), source.get("type_id"))){
            info = String.format("%s | %s", source.get("kafka_url"), source.get("topic"));
        } else if (Objects.equals(ConnectTypeEnum.FTP.getCode(), source.get("type_id"))) {
            info = String.format("%s:%s", source.get("host"), source.get("port"));
        } else if (Objects.equals(ConnectTypeEnum.Sap.getCode(), source.get("type_id"))) {
            info = String.format("%s:%s", source.get("host"), source.get("port"));
        } else if (Objects.equals(ConnectTypeEnum.JieKou.getCode(), source.get("type_id"))) {
            info = String.format("%s", source.get("Interface_url"));
        } else if (Objects.equals(ConnectTypeEnum.WebService.getCode(), source.get("type_id"))) {
            if (Objects.equals(3, source.get("request_type"))) {
                info = String.format("%s | %s", source.get("web_service_url"), "post-raw");
            } else {
                info = String.format("%s | %s", source.get("web_service_url"), source.get("function_name"));
            }
        } else if (Objects.equals(ConnectTypeEnum.OracleNTS.getCode(), source.get("type_id"))) {
            info = String.format("%s", source.get("oracle_nts_url"));
        } else {
            if (org.apache.commons.lang.StringUtils.isEmpty(source.get("db_name")+""))
                info = String.format("%s:%s", source.get("host"), source.get("port"));
            else
                info = String.format("%s:%s", source.get("host"), source.get("port"));
        }
        target.put("info",info);
        return target;
    }


    public String getRelationContent(Map<String,Object> source){
        StringBuilder builder = new StringBuilder();
        if (source.get("proc_names")!=null) {
            builder.append("关联的项目:<br/>").append(source.get("proc_names")).append("<br/>");
        }
        if (source.get("task_names")!=null) {
            builder.append("关联的元数据采集任务:<br/>").append(source.get("task_names")).append("<br/>");
        }
        if (source.get("rule_names")!=null) {
            builder.append("关联的质量规则:<br/>").append(source.get("rule_names")).append("<br/>");
        }
        if (source.get("service_names")!=null) {
            builder.append("关联的数据服务:<br/>").append(source.get("service_names")).append("<br/>");
        }

        if (source.get("sync_task_names")!=null) {
            builder.append("关联的整库同步任务:<br/>").append(source.get("sync_task_names")).append("<br/>");
        }
        String relationContent = builder.toString();
        return relationContent;
    }

}
